package com.imau.filter;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter",urlPatterns="/*")
public class LoginFilter implements Filter {

    //数组
    private String[] urls={"/css/","/images/","/js/","/index.jsp","/LoginServlet"};

    public void init(FilterConfig config) throws ServletException {
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        System.out.println("过滤器....");

        HttpServletRequest request=    (HttpServletRequest)servletRequest;
        HttpServletResponse response  = (HttpServletResponse)servletResponse;
        //1.获取请求路径

        String uri=request.getRequestURI();

        //2.比对


        for(String url:urls)
        {
            if(uri.contains(url))
            {
                //放行所有
                chain.doFilter(request,response);

                return;
            }
        }

        //3.校验

        //1.判断权限
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");

        if(user!=null)

        {
            chain.doFilter(request,response);

        }else {


            System.out.println("请先登录!!");
            response.sendRedirect(request.getContextPath()+"/index.jsp");
        }






    }

    public void destroy() {
    }


}
